#!/usr/bin/env bash

# Install stow from Homebrew
echo "正在检测和安装stow..."
brew list |grep stow > /dev/null 2>&1 || brew install stow
if [ $? -ne 0 ]; then
  echo "不能安装stow，请确认是否已安装Homebrew且连接互联网?"
  exit 1;
fi

# Update files from git
echo "正在从git更新文件..."
git pull origin master
if [ $? -ne 0 ]; then
  echo "不能更新dotfiles，请确认是否已安装git且连接互联网?"
  exit 2;
fi

# Update symbol links using stow
function stow_folder() {
  if [ "$2" == "" ]; then target=${HOME}; else target=$2; fi;
  echo "正在安装目录'$1'下文件和子目录的符号链接到目录'$target'..."
  for i in `ls -A $1`; do if [ -d "$1/$i" ]; then rm -fr $target/$i; fi; done;
  stow $(basename $1) -t $target
}

function stow_file() {
  if [ "$2" == "" ]; then target=${HOME}; else target=$2; fi;
  echo "正在安装目录'$1'和子目录下文件的符号链接到目录'$target'..."
  stow --adopt --no-folding $(basename $1) -t $target
}

function copy_file() {
  if [ "$2" == "" ]; then target=${HOME}; else target=$2; fi;
  echo "正在拷贝目录'$1'下文件和子目录的内容到目录'$target'..."
  for i in `ls -A $1`; do cp -af $1/$i $target/; done;
}

function doIt() {
  stow_folder ./link_folder
  stow_file ./link_file
  copy_file ./copy_file ${HOME}
  echo "dotfiles安装完毕。如果想立即生效，请根据shell类型执行'source ~/.bash_profile'或'source ~/.zshrc'"
}

pushd "$(cd "$(dirname "$0")"; pwd)" >/dev/null 2>&1
if [ "$1" == "--force" -o "$1" == "-f" ]; then
  doIt;
else
  read -p "安装dotfiles将覆盖Home目录下的相同配置，请确认是否继续? (y/n) " -n 1;
  echo "";
  if [[ $REPLY =~ ^[Yy]$ ]]; then doIt; fi;
fi;
popd >/dev/null 2>&1
